#include "window.h"

#include "compat.h"

namespace window {

std::wstring getVideoInfo() {
	const SDL_VideoInfo *info = SDL_GetVideoInfo();
	if(!info) {
		return L"SDL_GetVideoInfo failed.\n";
	} 
	std::wostringstream infostr;

	bool hw_available = info->hw_available;
	uint32 video_mem = info->video_mem;
	uint32 screen_w = info->current_w;
	uint32 screen_h = info->current_h;
	uint32 bpp = info->vfmt->BitsPerPixel;
	bool desktop = (SDL_GetVideoSurface() == NULL);

	SDL_version sdl_cver = {SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL};
	SDL_version sdl_lver = *SDL_Linked_Version();

	char videodriver[80];
	if(SDL_VideoDriverName(videodriver, 80) == 0) {
		throw util::Exception(L"SDL not initialized");
	}
	
	infostr << L"Video driver: " << wstr::toWide(videodriver) << std::endl;
	if(hw_available) {
		infostr << L"Video memory: " << info->video_mem << L"KB" << std::endl;
	}
	infostr << (desktop ? L"Desktop" : L"Window") << L" resolution: " << screen_w <<
		L"x" << screen_h << L"x" << bpp << L"bit" << std::endl;

	infostr << L"Compiled against SDL " << sdl_cver.major << L"."
		<< sdl_cver.minor << L"." << sdl_cver.patch << std::endl;
	infostr << L"Linked against SDL " << sdl_lver.major << L"."
		<< sdl_lver.minor << L"." << sdl_lver.patch << std::endl;

	return infostr.str();
}

std::vector<Resolution> &listVideoModes() {
	static std::vector<Resolution> resolutions;
	resolutions.clear();
	
	SDL_Rect** modes = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE|SDL_OPENGL);
	if(modes == (SDL_Rect**)0) {
		// No mode is ok
		return resolutions;
	}

	if(modes == (SDL_Rect**)-1) {
		std::wcout << L"All resolutions ok - not supported." << std::endl;
		assert(0);
	}

	// Make vector
	uint32 bpp = SDL_GetVideoInfo()->vfmt->BitsPerPixel;
	for(int i=0; modes[i]; ++i) {
		SDL_Rect *mode = modes[i];
		Resolution resolution = {modes[i]->w, modes[i]->h, bpp};
		resolutions.push_back(resolution);
	}

	return resolutions;
}

void openWindow(int width, int height, int bpp, bool fullscreen) {
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	uint32 flags = SDL_OPENGL;
	if(fullscreen) flags |= SDL_FULLSCREEN;

	SDL_Surface *new_surface = SDL_SetVideoMode(width, height, bpp, flags);
	if(new_surface == 0) {
		throw WindowError(wstr::toWide(SDL_GetError()));
	}

	info.width = width;
	info.height = height;
	info.aspect = (float)width / (float)height;
	info.fullscreen = fullscreen;
	info.flags = flags;
	info.surface = new_surface;
}


// Window information
//WindowInfo info;

}